<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>产品列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="../views/layui/css/layui.css" media="all">
    <!--[if lt IE 9]>
    <script src="__CSS__/html5shiv.min.js"></script>
    <script src="__CSS__/respond.min.js"></script>
    <![endif]-->
    <style>
        ol li a{
            color:#fff
        }
        dl>a>.layui-nav-more{
            display: none;
        }
        .layui-input-block{
            margin-left: 150px;
        }
        .layui-form-label{
            width: 120px;
        }
        .ddal {
            content: '';
            width: 0;
            height: 0;
            border-style: solid dashed dashed;
            border-color: #fff transparent transparent;
            overflow: hidden;
            cursor: pointer;
            transition: all .2s;
            -webkit-transition: all .2s;
            position: absolute;
            top: 50%;
            right: 3px;
            margin-top: -3px;
            border-width: 6px;
            border-top-color: rgba(255,255,255,.7);
        }
        .layui-layout-admin .layui-body{
            top:0 !important;
        }
        .layui-layout-admin .layui-side{
            top:0 !important;
        }
        .logo{
            width: 50px;
            display: inline-block;
            height: 21px;
        }
        .layui-table-cell{
            height: 92px !important;
        }
    </style>


</head>
<body>
    <div class="layui-layout layui-layout-admin">
      
        <!--侧边栏-->
        <div class="layui-side layui-bg-black">
            <div class="layui-side-scroll">
                <ul class="layui-nav layui-nav-tree">
                    <li class="layui-nav-item layui-nav-title" style="    display: flex;align-items: center;"><img class="logo" src="./views/img/logo.png" alt=""><a>管理菜单</a></li>
                    <li class="layui-nav-item layui-this"><a href="javascript:;">产品信息</a></li>
                    <li class="layui-nav-item "><a href="/city">城市数据</a></li>
                    <li class="layui-nav-item" style="height: 30px; text-align: center"></li>
                </ul>
            </div>
        </div>
        <div class="layui-body">
            <!--tab标签-->
            <div class="layui-tab layui-tab-brief">
                <ul class="layui-tab-title">
                    <li class="layui-this">数据列表</li>
                </ul>
              
                <div class="layui-tab-content" style="padding-top:0 ;">
                    <table id="test" lay-filter="test"></table>
                    <script type="text/html" id="toolbarDemo">
                        <div class="layui-btn-container">
                          <button class="layui-btn layui-btn-sm layui-bg-blue" id="reloadTest">
                            刷新
                          </button>
                          <!-- <button class="layui-btn layui-btn-sm layui-bg-blue" lay-event="add">
                            添加
                          </button> -->
                        </div>
                      </script>
                  
                </div>
            </div>
        </div>
    
    </div>
    <script type="text/html" id="content">
        <form class="layui-form" >
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block" style="color: red;">
                    需要换行的地方请添加`&lt;br/&gt;`
                </div>
              </div>
            <div class="layui-form-item">
              <label class="layui-form-label">产品名称</label>
              <div class="layui-input-block">
                <input type="text" name="title" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-form-item">
              <label class="layui-form-label">产品图片</label>
              <div class="layui-input-block">
                <input type="hidden" name="picture" value="">
                <button type="button" class="layui-btn" id="ID-upload-demo-btn">
                    <i class="layui-icon layui-icon-upload"></i> 上传图片
                  </button><span style="color: red;">图片尺寸：581*725</span>
                  <div style="width: 132px;">
                    <div class="layui-upload-list">
                      <img class="layui-upload-img" id="ID-upload-demo-img" style="width: auto; height: 92px;">
                      <div id="ID-upload-demo-text"></div>
                    </div>
                    <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo">
                      <div class="layui-progress-bar" lay-percent=""></div>
                    </div>
                  </div>
              </div>
            </div>
            <div class="layui-form-item layui-form-text">
              <label class="layui-form-label">中文内容</label>
              <div class="layui-input-block">
                <textarea name="zh" placeholder="请输入内容"  class="layui-textarea"></textarea>
              </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">英文内容</label>
                <div class="layui-input-block">
                  <textarea name="en" placeholder="请输入内容" class="layui-textarea"></textarea>
                </div>
              </div>
            <div class="layui-form-item">
                <label class="layui-form-label">排序</label>
                <div class="layui-input-block">
                    <input type="number" name="sort" value="0" lay-verify="required" placeholder="请输入数字，由大到小倒叙" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
              <div class="layui-input-block">
                <input type="hidden" name="_id" value="">
                <button type="button" class="layui-btn" lay-submit lay-filter="saveBtn">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
              </div>
            </div>
          </form>
    </script>
<!--JS引用-->
<script src="../views/jquery.min.js"></script>
<script src="../views/layui/layui.js"></script>

<script>
  function   getYMDHMS (timestamp){
        let time = new Date(timestamp)
        let year = time.getFullYear()
        let month = time.getMonth() + 1
        let date = time.getDate()
        let hours = time.getHours()
        let minute = time.getMinutes()
        let second = time.getSeconds()
        if (month < 10) { month = '0' + month }
        if (date < 10) { date = '0' + date }
        if (hours < 10) { hours = '0' + hours }
        if (minute < 10) { minute = '0' + minute }
        if (second < 10) { second = '0' + second }
        return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
    }
  function  getOpenWidthHeight () {
            var clienWidth = $(".layui-body").width();
            var clientHeight = $(".layui-body").height();
            var offsetLeft = $(".layui-body").offset().left;
            var offsetTop = $(".layui-body").offset().top;
            return [clienWidth, clientHeight, offsetTop, offsetLeft];
     }
     let upload;
     let element;
    layui.use(['form','layer','table','element'], function() {
        upload = layui.upload;
        element = layui.element;
        element.render('nav');
        var table = layui.table;
        var form = layui.form;
        var weidiantable =  table.render({
            elem: '#test'
            ,id:'test'
            ,maxHeight:'720px' 
            ,toolbar: '#toolbarDemo'
            ,defaultToolbar: ['filter', 'exports', 'print']   
            , url: "http://127.0.0.1:3000/getdata" //数据接口
            ,page: true //开启分页
            ,limit: 15
            ,limits:[15,100, 1000, 10000, 100000]
            ,cols: [[ //表头
                 {field: 'sort', title: '排序'}
                ,{field: 'title', title: '产品名'}
                ,{field: 'picture', title: '产品图',templet:function (d) {
                    
                        
                    let str = '<img  src="'+d.picture+'" style="width: auto; height: 92px;" />'
                   
                    return str

                }, align: "center"}
                ,{field: 'zh', title: '中文内容'}
                ,{field: 'en', title: '英文内容'}
                ,{title: '操作', minWidth: 150,  templet:function (d) {
                    
                        
                        let str = '<a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">修改</a>'
                       
                        return str

                    }, align: "center"}
            ]]
        });
      
        /**
         * toolbar事件监听
         */
         table.on('tool(test)', function (obj) {
            var data = obj.data;
            
            if (obj.event === 'edit') {
               
               
                var openWH = getOpenWidthHeight();

                var index = layer.open({
                    title: '编辑产品',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: $("#content").html(),
                    success:function(){
                        $("input[name='title']").val(data.title)
                        $("input[name='_id']").val(data._id)
                        $("input[name='picture']").val(data.picture)
                        $("input[name='sort']").val(data.sort)
                        $("textarea[name='zh']").val(data.zh)
                        $("textarea[name='en']").val(data.en)
                        $('#ID-upload-demo-img').attr('src', data.picture); // 图片链接（base64）
                        $('#ID-upload-demo-img').attr('lay-src', data.picture); // 图片链接（base64）
                        uploadFn()
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            }
        })
         table.on('toolbar(test)', function (obj) {
           
           
            if (obj.event === 'add') {   // 监听添加操作
                
                var openWH = getOpenWidthHeight();

                var index = layer.open({
                    title: '添加产品',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: $("#content").html(),
                    success:function(){
                        uploadFn()
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } 
        });
        //监听提交
        form.on('submit(saveBtn)', function (data) {
            
            // return 
            if(!data.field.picture){
                layer.msg('请上传图片');
                return false
            }
            $.ajax({
                url: "/setdata",
                type: "post",
                data: data.field,
                success: function (info) {
                    info = JSON.parse(info)
                    console.log(info)
                    if (info.code == 1) {
                        // 关闭弹出层
                        layer.msg(info.msg)
                        setTimeout(function () {
                            window.location.href = "";
                            layer.close(parentIndex);
                        }, 1000);

                    } else {
                        layer.msg(info.msg)
                    }
                },
                error(err) {

                }
            })
            return false;
        });
        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = data.field;
            console.log(result);
            //执行搜索重载
            table.reload('test', {
                page: {
                    curr: 1
                }
                , where: {
                    pid: result.pid
                }
            }, 'data');

            return false;
        });
        $("#reloadTest").click(function(){
            console.log("#reloadTest")
           window.location.href=""
        })
    })
    function uploadFn(){
        var uploadInst = upload.render({
            elem: '#ID-upload-demo-btn',
            url: '/upload', // 实际使用时改成您自己的上传接口即可。
            before: function(obj){
            // 预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#ID-upload-demo-img').attr('src', result); // 图片链接（base64）
            });
            
            element.progress('filter-demo', '0%'); // 进度条复位
            layer.msg('上传中', {icon: 16, time: 0});
            },
            done: function(res){
            // 若上传失败
            if(res.code !=200){
                return layer.msg('上传失败');
            }else{
                layer.msg('上传成功');
                $('#ID-upload-demo-img').attr('src',  res.url); // 图片链接（base64）
                $("input[name='picture']").val(res.url); // 图片链接（base64）
            }
            // 上传成功的一些操作
            // …
            $('#ID-upload-demo-text').html(''); // 置空上传失败的状态
            },
            error: function(){
                // 演示失败状态，并实现重传
                var demoText = $('#ID-upload-demo-text');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            },
            // 进度条
            progress: function(n, elem, e){
            element.progress('filter-demo', n + '%'); // 可配合 layui 进度条元素使用
            if(n == 100){
                layer.msg('上传完毕', {icon: 1});
            }
            }
        });
    }
       

</script>

</body>
</html>